tags:

views:

81

answers:

3

What's the best method to print out time in C in the format 2009‐08‐10
18:17:54.811?

Atm, I have Thu Sep 9 11:10:08 2010 but can't figure out the above.

+2  A: 

Use strftime().

#include <stdio.h>
#include <time.h>

int main()
{
    time_t timer;
    char buffer[25];
    struct tm* tm_info;

    time(&timer);
    tm_info = localtime(&timer);

    strftime(buffer, 25, "%Y:%m:%d%H:%M:%S", tm_info);
    puts(buffer);

    return 0;
}

For milliseconds part, have a look at this question. How to measure time in milliseconds using ANSI C?

Hamid Nazari
He's asked for C, so perhaps a cplusplus.com reference isn't so good. Try this: http://opengroup.org/onlinepubs/007908799/xsh/strftime.html . Also you've put the wrong format string in.
Jack Kelly
@Jack thanks for mentioning that Jack. I fixed the format string.
Hamid Nazari
@Hamid Nazari: It's an even better answer now, and props for looking up how to handle the millisecond part. I think your buffer is now a little longer than it needs to be, though.
Jack Kelly
Better to be longer than shorter :-)
paxdiablo
+1  A: 

You could use strftime, but struct tm doesn't have resolution for parts of seconds. I'm not sure if that's absolutely required for your purposes.

struct tm tm;
/* Set tm to the correct time */
char s[20]; /* strlen("2009-08-10 18:17:54") + 1 */
strftime(s, 20, "%F %H:%M:%s", &tm);
Jack Kelly
+1  A: 

time.h defines a strftime function which can give you a textual representation of a time_t using something like:

#include <stdio.h>
#include <time.h>
int main (void) {
    char buff[100];
    time_t now = time (0);
    strftime (buff, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now));
    printf ("%s\n", buff);
    return 0;
}

but that won't give you sub-second resolution since that's not available from a time_t. It outputs:

2010-09-09 10:08:34.000

If you're really constrained by the specs and do not want the space between the day and hour, just remove it from the format string.

paxdiablo
+1 for the expedient trick for filling out the display to the millisecond. I had a customer once that wanted me to do that, but with non-zero digits so it looked like there was significance there. I talked him out of it but agreed to put in zeros.
RBerteig
A friend of mine (not me of course) once used a similar trick - they kept statics containing the last second and "millisecond". Where the second hadn't changed from the last time, they just added a random value between 1 and 200 to millisec (making sure it didn't go past 999 of course - the actual max for the rand() was always the min of 200 and half the distance to 999). Where the second did change, they just set millisec to 0 before the add. Nice seemingly random but properly sequenced milliseconds and the customer was none the wiser :-)
paxdiablo